<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\CartController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\UserAddressController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\SearchController;
use App\Http\Controllers\Admin\AdminDashboardController;
use App\Http\Controllers\Admin\AdminProductController;
use App\Http\Controllers\Admin\AdminProductImageController;
use App\Http\Controllers\Admin\AdminCategoryController;
use App\Http\Controllers\Admin\AdminOrderController;
use App\Http\Controllers\Admin\AdminUserController;
use App\Http\Controllers\Admin\AdminSettingController;
use App\Http\Controllers\Admin\AdminSpecificationController;
use App\Http\Controllers\Admin\AdminVariantController;
use App\Http\Controllers\Admin\AdminSystemSettingController;
use App\Http\Controllers\Admin\AdminSpecificationTemplateController;
use App\Http\Controllers\Admin\AdminLogController;
use App\Http\Controllers\Admin\AdminCouponController;
use App\Http\Controllers\CouponController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\QueueController;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// 前端商城页面
Route::get('/', [HomeController::class, 'index'])->name('home');
Route::get('/categories', [CategoryController::class, 'index'])->name('categories');
Route::get('/categories/{slug}', [CategoryController::class, 'show'])->name('category.show');
Route::get('/products/{slug}', [ProductController::class, 'show'])->name('product.show');

// 搜索相关路由
Route::get('/search', [SearchController::class, 'index'])->name('search.index');
Route::get('/api/search/suggestions', [SearchController::class, 'suggestions'])->name('search.suggestions');
Route::get('/api/search/history', [SearchController::class, 'history'])->name('search.history');
Route::delete('/api/search/history/{id}', [SearchController::class, 'deleteHistory'])->name('search.history.delete');
Route::delete('/api/search/history', [SearchController::class, 'clearHistory'])->name('search.history.clear');
Route::get('/api/search/hot', [SearchController::class, 'hot'])->name('search.hot');


// 购物车
Route::get('/cart', [CartController::class, 'index'])->name('cart');
Route::post('/cart/add', [CartController::class, 'add'])->name('cart.add');
Route::post('/cart/update', [CartController::class, 'update'])->name('cart.update');
Route::post('/cart/remove', [CartController::class, 'remove'])->name('cart.remove');
Route::post('/cart/batch-remove', [CartController::class, 'batchRemove'])->name('cart.batch-remove');
Route::post('/cart/clear', [CartController::class, 'clear'])->name('cart.clear');
Route::post('/cart/batch-move-to-favorites', [CartController::class, 'batchMoveToFavorites'])->name('cart.batch-move-to-favorites');
Route::post('/cart/toggle-select', [CartController::class, 'toggleSelect'])->name('cart.toggle-select');
Route::post('/cart/toggle-select-all', [CartController::class, 'toggleSelectAll'])->name('cart.toggle-select-all');
Route::post('/cart/clear-invalid', [CartController::class, 'clearInvalid'])->name('cart.clear-invalid');
// 结算相关路由
Route::middleware('auth')->group(function () {
    Route::get('/checkout', [OrderController::class, 'checkout'])->name('checkout');
    Route::post('/checkout/buy-now', [OrderController::class, 'buyNow'])->name('checkout.buy-now');
    Route::post('/checkout/submit', [OrderController::class, 'submit'])->name('checkout.submit');
    Route::post('/checkout/calculate-price', [OrderController::class, 'calculatePrice'])->name('checkout.calculate-price');
});

// 订单相关路由
Route::middleware('auth')->group(function () {
    Route::get('/orders', [OrderController::class, 'index'])->name('orders.index');
    
    // 支付相关路由（更具体的路由放在前面）
    Route::get('/orders/{orderNumber}/payment', [PaymentController::class, 'show'])->name('payment.show');
    Route::post('/orders/{orderNumber}/payment', [PaymentController::class, 'pay'])->name('payment.pay');
    Route::get('/orders/{orderNumber}/payment/status', [PaymentController::class, 'status'])->name('payment.status');
    Route::post('/orders/{orderNumber}/payment/cancel', [PaymentController::class, 'cancel'])->name('payment.cancel');
    
    // 订单详情路由（放在支付路由之后）
    Route::get('/orders/{orderNumber}', [OrderController::class, 'show'])->name('order.show');
    Route::post('/orders/{orderNumber}/cancel', [OrderController::class, 'userCancel'])->name('order.cancel');
    Route::post('/orders/{orderNumber}/confirm-delivery', [OrderController::class, 'confirmDelivery'])->name('order.confirm-delivery');
    
    // 售后相关路由
    Route::prefix('after-sales')->name('after-sales.')->group(function () {
        Route::get('/', [\App\Http\Controllers\AfterSalesController::class, 'index'])->name('index');
        Route::get('/create', [\App\Http\Controllers\AfterSalesController::class, 'create'])->name('create');
        Route::post('/', [\App\Http\Controllers\AfterSalesController::class, 'store'])->name('store');
        Route::get('/{afterSalesRequest}', [\App\Http\Controllers\AfterSalesController::class, 'show'])->name('show');
        Route::post('/{afterSalesRequest}/cancel', [\App\Http\Controllers\AfterSalesController::class, 'cancel'])->name('cancel');
        Route::post('/{afterSalesRequest}/logistics', [\App\Http\Controllers\AfterSalesController::class, 'storeLogistics'])->name('logistics.store');
        Route::post('/{afterSalesRequest}/confirm-delivered', [\App\Http\Controllers\AfterSalesController::class, 'confirmDelivered'])->name('confirm-delivered');
    });
    
    // 优惠券相关路由
    Route::prefix('coupons')->name('coupons.')->group(function () {
        Route::get('/', [CouponController::class, 'index'])->name('index');
        Route::get('/my', [CouponController::class, 'myCoupons'])->name('my');
        Route::post('/{id}/receive', [CouponController::class, 'receive'])->name('receive');
        Route::get('/available', [CouponController::class, 'available'])->name('available');
    });
    
    // 通知相关路由
    Route::prefix('notifications')->name('notifications.')->group(function () {
        Route::get('/', [\App\Http\Controllers\NotificationController::class, 'index'])->name('index');
        Route::post('/mark-as-read', [\App\Http\Controllers\NotificationController::class, 'markAsRead'])->name('mark-as-read');
        Route::post('/mark-all-as-read', [\App\Http\Controllers\NotificationController::class, 'markAllAsRead'])->name('mark-all-as-read');
        Route::delete('/', [\App\Http\Controllers\NotificationController::class, 'destroy'])->name('destroy');
        Route::get('/unread-count', [\App\Http\Controllers\NotificationController::class, 'unreadCount'])->name('unread-count');
        Route::get('/recent', [\App\Http\Controllers\NotificationController::class, 'recent'])->name('recent');
    });
});

// 支付回调路由（不需要认证）
Route::post('/payment/callback/alipay', [PaymentController::class, 'alipayCallback'])->name('payment.callback.alipay');
Route::post('/payment/callback/wechat', [PaymentController::class, 'wechatCallback'])->name('payment.callback.wechat');

Route::get('/dashboard', function () {
    return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    // 用户中心
    Route::get('/profile', [UserController::class, 'profile'])->name('profile');
    Route::patch('/profile', [UserController::class, 'updateProfile'])->name('profile.update');
    
    // 地址管理
    Route::get('/addresses', [UserAddressController::class, 'index'])->name('addresses.index');
    Route::post('/addresses', [UserAddressController::class, 'store'])->name('addresses.store');
    Route::put('/addresses/{address}', [UserAddressController::class, 'update'])->name('addresses.update');
    Route::delete('/addresses/{address}', [UserAddressController::class, 'destroy'])->name('addresses.destroy');
    Route::post('/addresses/{address}/default', [UserAddressController::class, 'setDefault'])->name('addresses.default');
    
    // 账户设置
    Route::get('/settings', [UserController::class, 'settings'])->name('settings');
    Route::patch('/settings', [UserController::class, 'updateSettings'])->name('settings.update');

    // 原有的个人资料管理（保留用于兼容）
    Route::get('/profile/edit', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

// 后台管理路由组
Route::prefix('admin')->middleware(['auth', 'log.admin'])->group(function () {
    // 默认重定向到仪表板
    Route::get('/', function () {
        return redirect()->route('admin.dashboard');
    });
    
    // 仪表板
    Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('admin.dashboard');
    
    // 产品管理
    Route::resource('products', AdminProductController::class)->names([
        'index' => 'admin.products.index',
        'create' => 'admin.products.create',
        'store' => 'admin.products.store',
        'show' => 'admin.products.show',
        'edit' => 'admin.products.edit',
        'update' => 'admin.products.update',
        'destroy' => 'admin.products.destroy',
    ]);

    // 产品图片管理
    Route::get('products/{product}/images', [AdminProductImageController::class, 'index'])->name('admin.products.images.index');
    Route::post('products/{product}/images', [AdminProductImageController::class, 'store'])->name('admin.products.images.store');
    Route::delete('products/{product}/images/{image}', [AdminProductImageController::class, 'destroy'])->name('admin.products.images.destroy');
    Route::post('products/{product}/images/{image}/primary', [AdminProductImageController::class, 'setPrimary'])->name('admin.products.images.primary');
    Route::post('products/{product}/images/sort', [AdminProductImageController::class, 'sort'])->name('admin.products.images.sort');
    Route::post('products/{product}/toggle-status', [AdminProductController::class, 'toggleStatus'])->name('admin.products.toggle-status');
    Route::post('products/{product}/toggle-featured', [AdminProductController::class, 'toggleFeatured'])->name('admin.products.toggle-featured');
    Route::get('products/{product}/variants', [AdminProductController::class, 'variants'])->name('admin.products.variants');
    
    // 变体管理
    Route::resource('variants', AdminVariantController::class)->only(['show', 'update', 'destroy'])->names([
        'show' => 'admin.variants.show',
        'update' => 'admin.variants.update',
        'destroy' => 'admin.variants.destroy',
    ]);
    Route::post('variants/{variant}/toggle-status', [AdminVariantController::class, 'toggleStatus'])->name('admin.variants.toggle-status');
    
    // 分类管理
    Route::resource('categories', AdminCategoryController::class)->names([
        'index' => 'admin.categories.index',
        'create' => 'admin.categories.create',
        'store' => 'admin.categories.store',
        'show' => 'admin.categories.show',
        'edit' => 'admin.categories.edit',
        'update' => 'admin.categories.update',
        'destroy' => 'admin.categories.destroy',
    ]);
    Route::post('categories/{category}/toggle-status', [AdminCategoryController::class, 'toggleStatus'])->name('admin.categories.toggle-status');
    
    // 规格管理
    Route::resource('specifications', AdminSpecificationController::class)->names([
        'index' => 'admin.specifications.index',
        'create' => 'admin.specifications.create',
        'store' => 'admin.specifications.store',
        'show' => 'admin.specifications.show',
        'edit' => 'admin.specifications.edit',
        'update' => 'admin.specifications.update',
        'destroy' => 'admin.specifications.destroy',
    ]);
    Route::post('specifications/{specification}/toggle-status', [AdminSpecificationController::class, 'toggleStatus'])->name('admin.specifications.toggle-status');
    
    // 规格模板管理
    Route::resource('specification-templates', AdminSpecificationTemplateController::class)->names([
        'index' => 'admin.specification-templates.index',
        'create' => 'admin.specification-templates.create',
        'store' => 'admin.specification-templates.store',
        'show' => 'admin.specification-templates.show',
        'edit' => 'admin.specification-templates.edit',
        'update' => 'admin.specification-templates.update',
        'destroy' => 'admin.specification-templates.destroy',
    ]);
    Route::post('specification-templates/{template}/toggle-status', [AdminSpecificationTemplateController::class, 'toggleStatus'])->name('admin.specification-templates.toggle-status');
    Route::get('categories/{category}/templates', [AdminSpecificationTemplateController::class, 'getTemplatesForCategory'])->name('admin.categories.templates');
    
    // 优惠券管理
    Route::resource('coupons', AdminCouponController::class)->names([
        'index' => 'admin.coupons.index',
        'create' => 'admin.coupons.create',
        'store' => 'admin.coupons.store',
        'edit' => 'admin.coupons.edit',
        'update' => 'admin.coupons.update',
        'destroy' => 'admin.coupons.destroy',
    ]);
    Route::get('coupons/{coupon}/distribute', [AdminCouponController::class, 'distribute'])->name('admin.coupons.distribute');
    Route::post('coupons/{coupon}/send-to-users', [AdminCouponController::class, 'sendToUsers'])->name('admin.coupons.send-to-users');
    Route::get('coupons/{coupon}/statistics', [AdminCouponController::class, 'statistics'])->name('admin.coupons.statistics');
    
    // 订单管理
    Route::get('orders', [AdminOrderController::class, 'index'])->name('admin.orders.index');
    Route::get('orders/{order:order_number}', [AdminOrderController::class, 'show'])->name('admin.orders.show');
    Route::patch('orders/{order:order_number}/status', [AdminOrderController::class, 'updateStatus'])->name('admin.orders.update-status');
    Route::post('orders/{order:order_number}/mark-paid', [AdminOrderController::class, 'markAsPaid'])->name('admin.orders.mark-paid');
    Route::post('orders/{order:order_number}/ship', [AdminOrderController::class, 'ship'])->name('admin.orders.ship');
    Route::post('orders/{order:order_number}/cancel', [AdminOrderController::class, 'cancel'])->name('admin.orders.cancel');
    
    // 批量操作
    Route::post('orders/batch-mark-paid', [AdminOrderController::class, 'batchMarkAsPaid'])->name('admin.orders.batch-mark-paid');
    Route::post('orders/batch-ship', [AdminOrderController::class, 'batchShip'])->name('admin.orders.batch-ship');
    Route::post('orders/batch-cancel', [AdminOrderController::class, 'batchCancel'])->name('admin.orders.batch-cancel');
    
    // 售后管理
    Route::prefix('after-sales')->name('admin.after-sales.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'index'])->name('index');
        Route::get('/{afterSalesRequest}', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'show'])->name('show');
        Route::post('/{afterSalesRequest}/approve', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'approve'])->name('approve');
        Route::post('/{afterSalesRequest}/reject', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'reject'])->name('reject');
        Route::post('/{afterSalesRequest}/process', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'process'])->name('process');
        Route::post('/{afterSalesRequest}/complete', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'complete'])->name('complete');
        Route::post('/{afterSalesRequest}/logistics', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'addLogistics'])->name('logistics');
        // 换货流程路由
        Route::post('/{afterSalesRequest}/confirm-return', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'confirmReturnReceived'])->name('confirm-return');
        Route::post('/{afterSalesRequest}/send-new', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'sendNewProduct'])->name('send-new');
        Route::post('/{afterSalesRequest}/confirm-delivered', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'confirmNewDelivered'])->name('confirm-delivered');
        Route::post('/{afterSalesRequest}/complete-exchange', [\App\Http\Controllers\Admin\AdminAfterSalesController::class, 'completeExchange'])->name('complete-exchange');
    });
    
    // 用户管理
    Route::resource('users', AdminUserController::class)->names([
        'index' => 'admin.users.index',
        'create' => 'admin.users.create',
        'store' => 'admin.users.store',
        'show' => 'admin.users.show',
        'edit' => 'admin.users.edit',
        'update' => 'admin.users.update',
        'destroy' => 'admin.users.destroy',
    ]);
    Route::post('users/{user}/reset-password', [AdminUserController::class, 'resetPassword'])->name('admin.users.reset-password');
    Route::post('users/{user}/toggle-email-verification', [AdminUserController::class, 'toggleEmailVerification'])->name('admin.users.toggle-email-verification');
    
    // 系统设置（原有）
    Route::get('settings', [AdminSettingController::class, 'index'])->name('admin.settings');
    Route::put('settings', [AdminSettingController::class, 'update'])->name('admin.settings.update');
    
    // 系统配置管理
    Route::get('system-settings', [AdminSystemSettingController::class, 'index'])->name('admin.system-settings');
    Route::post('system-settings', [AdminSystemSettingController::class, 'update'])->name('admin.system-settings.update');
    
    // 操作日志管理
    Route::get('logs', [AdminLogController::class, 'index'])->name('admin.logs.index');
    Route::get('logs/{log}', [AdminLogController::class, 'show'])->name('admin.logs.show');
    Route::post('logs/cleanup', [AdminLogController::class, 'cleanup'])->name('admin.logs.cleanup');
    
    // 队列管理
    Route::get('queue', [QueueController::class, 'index'])->name('admin.queue.index');
    Route::post('queue/retry', [QueueController::class, 'retryFailedJobs'])->name('admin.queue.retry');
    Route::post('queue/clear', [QueueController::class, 'clearQueue'])->name('admin.queue.clear');
    Route::delete('queue/failed/{job}', [QueueController::class, 'deleteFailedJob'])->name('admin.queue.delete-failed');
    
    // 物流公司管理
    Route::resource('logistics-companies', \App\Http\Controllers\Admin\LogisticsCompanyController::class);
    Route::get('api/logistics-companies/active', [\App\Http\Controllers\Admin\LogisticsCompanyController::class, 'getActiveCompanies'])->name('admin.logistics-companies.active');
    
    // 通知管理
    Route::get('/notifications/send', [\App\Http\Controllers\Admin\AdminNotificationController::class, 'create'])->name('admin.notifications.create');
    Route::post('/notifications/send', [\App\Http\Controllers\Admin\AdminNotificationController::class, 'send'])->name('admin.notifications.send');
});

// API 路由
Route::prefix('api')->group(function () {
    // 地址相关API
    Route::get('provinces', [App\Http\Controllers\Api\AddressController::class, 'provinces']);
    Route::get('cities', [App\Http\Controllers\Api\AddressController::class, 'cities']);
    Route::get('districts', [App\Http\Controllers\Api\AddressController::class, 'districts']);
    
    // 地址选择API（用于结算页面）
    Route::get('cities', [App\Http\Controllers\OrderController::class, 'getCities'])->name('api.cities');
    Route::get('districts', [App\Http\Controllers\OrderController::class, 'getDistricts'])->name('api.districts');
});

require __DIR__.'/auth.php';
